package com.ba.grain;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

import util.FoodType;
import util.Grade;
import util.Site;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.ActionMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class CollectActivity extends Activity implements OnItemSelectedListener, OnClickListener {
	private static final int REQUEST_IMAGE = 0x1000;
	private EditText mBuyPrice, mTradePrice, mDayRetailPrice, mWeekRetailPrice;
	private TextView mCollector, mCompany;
	private Spinner mFoodType, mGrade, mCollectionStation;
	private Button mButtonSave, mButtonReport, mButtonPicReport, mButtonBack2List;
	public ActionMode mActionMode;
	/**
	 * 即将上报的key
	 */
//	private String mReportKey;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.data_collection);
		initViews();
	}

	private void initViews() {
		mCompany = (TextView) findViewById(R.id.company);
		mCompany.setText(String.valueOf(G.sUser.department_id));
		mBuyPrice = (EditText) findViewById(R.id.buy_price);
		mTradePrice = (EditText) findViewById(R.id.trade_price);
		mDayRetailPrice = (EditText) findViewById(R.id.day_retail_price);
		mWeekRetailPrice = (EditText) findViewById(R.id.week_retail_price);
		mCollectionStation = (Spinner) findViewById(R.id.sp_collection_station);
		ArrayAdapter<?> adapter = new ArrayAdapter<Site>(this,
				android.R.layout.simple_spinner_item, G.sSites);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mCollectionStation.setAdapter(adapter);
		mCollectionStation.setOnItemSelectedListener(this);

		mCollector = (TextView) findViewById(R.id.collector);
		mFoodType = (Spinner) findViewById(R.id.sp_type);
		mFoodType.setOnItemSelectedListener(this);
		onItemSelected(mCollectionStation, null, 0, 0);

		mGrade = (Spinner) findViewById(R.id.sp_level);
		onItemSelected(mFoodType, null, 0, 0);
		mCollector.setText(PreferenceManager.getDefaultSharedPreferences(this).getString(
				LoginActivity.KEY_COLLECTOR, null));

		mButtonSave = (Button) findViewById(R.id.save);
		mButtonReport = (Button) findViewById(R.id.report);
		mButtonPicReport = (Button) findViewById(R.id.pic_report);
		mButtonBack2List = (Button) findViewById(R.id.back2list);
		mButtonSave.setOnClickListener(this);
		mButtonPicReport.setOnClickListener(this);
		mButtonReport.setOnClickListener(this);
		mButtonBack2List.setOnClickListener(this);
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		if (parent == mCollectionStation) {
			Site site = (Site) mCollectionStation.getSelectedItem();
			if (site == null) {
				onNothingSelected(parent);
				return;
			}
			ArrayAdapter<FoodType> adapter = new ArrayAdapter<FoodType>(this,
					android.R.layout.simple_spinner_item, site.foods);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mFoodType.setAdapter(adapter);
		} else if (mFoodType == parent) {
			FoodType type = (FoodType) mFoodType.getSelectedItem();
			if (type == null) {
				onNothingSelected(parent);
				return;
			}
			ArrayAdapter<Grade> adapter = new ArrayAdapter<Grade>(this,
					android.R.layout.simple_spinner_item, type.grades);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mGrade.setAdapter(adapter);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		if (parent == mCollectionStation) {
			ArrayAdapter<FoodType> adapter = new ArrayAdapter<FoodType>(this,
					android.R.layout.simple_spinner_item, new FoodType[0]);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mFoodType.setAdapter(adapter);
		} else if (mFoodType == parent) {
			ArrayAdapter<Grade> adapter = new ArrayAdapter<Grade>(this,
					android.R.layout.simple_spinner_item, new Grade[0]);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mGrade.setAdapter(adapter);
		}
	}

	@Override
	public void onClick(View v) {
		if (v == mButtonReport) {
			ListItem item = new ListItem();
			if (!initItem(item)) {
				return;
			}
			final String key = doSave(item);
			if (G.sSocket == null) {
				noLoginReport(key, null);
			} else {
				report(key, null);
			}
		} else if (v == mButtonSave) {
			ListItem item = new ListItem();
			if (!initItem(item)) {
				return;
			}
			doSave(item);
			Toast.makeText(this, "保存成功。", Toast.LENGTH_SHORT).show();
		} else if (mButtonPicReport == v) {
			ListItem item = new ListItem();
			if (!initItem(item)) {
				return;
			}
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File dir = makeRootDir();
			String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(System
					.currentTimeMillis()));
			name = String.format("%s_%s", RecordActivity.NAME_RECORDS, name);
			try {
				mFileUpload = File.createTempFile(name, ".jpg", dir);
				Uri uri = Uri.fromFile(mFileUpload);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				intent.putExtra("NAME", name);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				startActivityForResult(intent, REQUEST_IMAGE);
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				return;
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && REQUEST_IMAGE == requestCode) {
			ListItem item = new ListItem();
			if (!initItem(item)) {
				return;
			}
			String reportKey = doSave(item);
			if (G.sSocket == null) {
				String path = mFileUpload != null ? path = mFileUpload.getPath() : null;
				noLoginReport(reportKey, path);
			} else {
				String path = mFileUpload != null ? path = mFileUpload.getPath() : null;
				report(reportKey, path);
				mFileUpload = null;
			}
		}
		if (resultCode == RESULT_CANCELED && REQUEST_IMAGE == requestCode) {
			if (mFileUpload != null) {
				mFileUpload.delete();
			}
		}
	}

	// 把该工作转给ReportActivity
	private void report(String key, String filePath) {
		final Intent intent = new Intent(this, ReportActivity.class);
		intent.putExtra(ReportActivity.KEY_REPORT_ITEM_KEY, key);
		intent.putExtra(ReportActivity.KEY_REPORT_FILE_PATH, filePath);
		startActivity(intent);
	}

	// 把该工作转给MainActivity
	private void noLoginReport(String key, String path) {
		Intent intent = new Intent();
		intent.putExtra(ReportActivity.KEY_REPORT_ITEM_KEY, key);
		intent.putExtra(ReportActivity.KEY_REPORT_FILE_PATH, path);
		setResult(RESULT_OK, intent);
		finish();
	}

	public static void doSave(Context context, ListItem... items) {
		SharedPreferences sp = context.getSharedPreferences(RecordActivity.NAME_RECORDS,
				MODE_PRIVATE);
		Editor editor = sp.edit();
		for (ListItem item : items) {
			if (item.key == null) {
				item.key = String.valueOf(System.currentTimeMillis());
				String.format("", 0);
				SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH.mm");
				item.mSaveDateTime = sdf.format(new java.util.Date());
				// item.mSaveDateTime = String.for
			}
			editor.putString(item.key, item.toString());
		}
		editor.commit();
	}

	private String doSave(ListItem item) {
		doSave(this, item);
		clear(mBuyPrice, mTradePrice, mDayRetailPrice, mWeekRetailPrice);
		return item.key;
	}

	/**
	 * 拍照上傳時的文件
	 */
	private File mFileUpload;

	private boolean checkLegal(EditText... views) {
		for (int i = 0; i < views.length; i++) {
			EditText view = views[i];
			if (TextUtils.isEmpty(view.getText().toString())) {
				view.setError("请输入完整信息");
				view.requestFocus();
				return false;
			}
		}
		return true;
	}

	private boolean initItem(ListItem item) {

		boolean legal = checkLegal(mBuyPrice, mTradePrice, mDayRetailPrice, mWeekRetailPrice);
		if (!legal) {
			return false;
		}
		if (legal) {
			try {
				item.buyPrice = Float.parseFloat(mBuyPrice.getText().toString());
			} catch (Exception e) {
				mBuyPrice.setError("请输入合法价格");
				mBuyPrice.requestFocus();
				return false;
			}
			try {
				item.tradePrice = Float.parseFloat(mTradePrice.getText().toString());
			} catch (Exception e) {
				mTradePrice.setError("请输入合法价格");
				mTradePrice.requestFocus();
				return false;
			}
			try {
				item.dayRetailPrice = Float.parseFloat(mDayRetailPrice.getText().toString());
			} catch (Exception e) {
				mDayRetailPrice.setError("请输入合法价格");
				mDayRetailPrice.requestFocus();
				return false;
			}
			try {
				item.weekRetailPrice = Float.parseFloat(mWeekRetailPrice.getText().toString());
			} catch (Exception e) {
				mWeekRetailPrice.setError("请输入合法价格");
				mWeekRetailPrice.requestFocus();
				return false;
			}
		}
		Site site = (Site) mCollectionStation.getSelectedItem();
		item.site_id = site.id;
		item.mSite = site;
		FoodType ft = (FoodType) mFoodType.getSelectedItem();
		item.foodType_id = ft.id;
		item.mFoodType = ft;
		Grade gd = (Grade) mGrade.getSelectedItem();
		item.grade_id = gd.id;
		item.mGrade = gd;
		return true;
	}

	public static void clear(EditText... views) {
		for (int i = 0; i < views.length; i++) {
			EditText view = views[i];
			view.setText("");
		}
	}

	private static final String ROOT = "Grain";

	public static File makeRootDir() {
		File dir = new File(Environment.getExternalStorageDirectory(), ROOT);
		dir.mkdirs();// 创建文件夹
		return dir;
	}
}
